package com.ant.storage.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.teaopenapi.models.Config;
import com.ant.storage.common.Constants;
import com.ant.storage.dto.DingDto;
import com.ant.storage.dto.FundsDto;
import com.ant.storage.dto.ReimbursementProjectDto;
import com.ant.storage.handler.AntException;
import com.ant.storage.pojo.Allocation;
import com.ant.storage.pojo.AuditList;
import com.ant.storage.vo.CommodityVo;
import com.ant.storage.vo.PickingCommodityVo;
import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.DingTalkClient;
import com.dingtalk.api.request.*;
import com.dingtalk.api.response.*;
import com.taobao.api.ApiException;
import org.apache.commons.lang3.StringUtils;

import java.math.BigDecimal;
import java.util.*;

public class DingDingUtil {


    public static Long getPersonneDepld(String userId, String accessToken) throws ApiException {
        DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk" +
                ".com/topapi/v2/department/listparentbyuser");
        OapiV2DepartmentListparentbyuserRequest req = new OapiV2DepartmentListparentbyuserRequest();
        req.setUserid(userId);
        OapiV2DepartmentListparentbyuserResponse rsp = client.execute(req, accessToken);
        if (!rsp.getErrcode().equals(0L)) {
            throw new AntException("获取钉钉信息失败" + rsp.getErrmsg());
        }
        return rsp.getResult().getParentList().get(0).getParentDeptIdList().get(0);
    }

    /**
     * 通过app_key与app_secret获取token
     *
     * @return
     * @throws ApiException
     */
    public static String obtainToken() throws ApiException {
        DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/gettoken");
        OapiGettokenRequest request = new OapiGettokenRequest();
        request.setAppkey(Constants.APPKEY);
        request.setAppsecret(Constants.APPSECRET);
        request.setHttpMethod("GET");
        OapiGettokenResponse response = client.execute(request);
        return response.getAccessToken();
    }

    /**
     * 根据电话号码获取userId
     *
     * @param phone 电话号码
     * @throws ApiException
     */
    public static String queryUserId(String phone) throws ApiException {
        DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/v2/user/getbymobile?");
        OapiV2UserGetbymobileRequest req = new OapiV2UserGetbymobileRequest();
        req.setMobile(phone);
        OapiV2UserGetbymobileResponse rsp = client.execute(req, obtainToken());
        if (JSONObject.parseObject(rsp.getBody()).get("errmsg").equals("ok")) {
            return String.valueOf(JSONObject.parseObject(rsp.getBody()).getJSONObject("result").get("userid"));
        }
        throw new AntException((int) JSONObject.parseObject(rsp.getBody()).get("errcode"),
                JSONObject.parseObject(rsp.getBody()).get("errmsg").toString());
    }

    //获取部门Id
    public static void queryDeptId() throws ApiException {
        DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/user/listid");
        OapiUserListidRequest req = new OapiUserListidRequest();
        req.setDeptId(1L);
        String access_token = obtainToken();
        OapiUserListidResponse rsp = client.execute(req, access_token);
        System.out.println(rsp.getBody());
    }

    //查看回调失败实例
    public static void query() throws ApiException {
        DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk" +
                ".com/call_back/get_call_back_failed_result");
        OapiCallBackGetCallBackFailedResultRequest req = new OapiCallBackGetCallBackFailedResultRequest();
        req.setHttpMethod("GET");
        String access_token = obtainToken();
        OapiCallBackGetCallBackFailedResultResponse rsp = client.execute(req, access_token);
        System.out.println(rsp.getBody());
    }

    /**
     * 根据UserId查看员工详情资料
     *
     * @param userId
     * @throws ApiException
     */
    public static String queryUser(String userId, String access_token) throws ApiException {
        DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/v2/user/get");
        OapiV2UserGetRequest req = new OapiV2UserGetRequest();
        req.setUserid(userId);
        OapiV2UserGetResponse rsp = client.execute(req, access_token);
        if (JSONObject.parseObject(rsp.getBody()).get("errmsg").equals("ok")) {
            return rsp.getBody();
        }
        throw new AntException((int) JSONObject.parseObject(rsp.getBody()).get("errcode"),
                JSONObject.parseObject(rsp.getBody()).get("errmsg").toString());
    }

    /**
     * 使用 Token 初始化账号Client
     *
     * @return Client
     * @throws Exception
     */
    public static com.aliyun.dingtalkworkflow_1_0.Client createClient() throws Exception {
        Config config = new Config();
        config.protocol = "https://oapi.dingtalk.com/topapi/processinstance/create";
        config.regionId = Constants.AGENTID.toString();
        return new com.aliyun.dingtalkworkflow_1_0.Client(config);
    }




    /**
     * 采购申请审批
     * 开发文档 https://open.dingtalk.com/document/orgapp-server/create-an-approval-instance
     *
     * @param dto 关联商品信息
     * @throws ApiException
     */
    public static String OldGoodeAppalyAndApprove(DingDto dto) throws Exception {
        DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/processinstance/create");
        OapiProcessinstanceCreateRequest req = new OapiProcessinstanceCreateRequest();
        req.setAgentId(Constants.AGENTID);
        //模板code
        req.setProcessCode(Constants.ALLOCATION_PURCHASE_REQUISITION);
        //发起人userId
        req.setOriginatorUserId(dto.getOriginator_userid());
        //发起人部门Id
        req.setDeptId(Long.valueOf(dto.getDeptId()));
        req.setCcPosition("START");
        //申请部门
        List<OapiProcessinstanceCreateRequest.FormComponentValueVo> formComponentValueVoList = new ArrayList<>();

        OapiProcessinstanceCreateRequest.FormComponentValueVo formComponentValueVo =
                new OapiProcessinstanceCreateRequest.FormComponentValueVo();
        formComponentValueVoList.add(formComponentValueVo);
        formComponentValueVo.setName("申请部门");
        formComponentValueVo.setValue(dto.getCity() + "-" + dto.getDepartment());
        //备注
        OapiProcessinstanceCreateRequest.FormComponentValueVo formComponentValueVo1 =
                new OapiProcessinstanceCreateRequest.FormComponentValueVo();

        formComponentValueVo1.setName("备注");
        if (dto.getRemarks() == null || dto.getRemarks().equals("")) {
            formComponentValueVo1.setValue("");
        } else {
            formComponentValueVo1.setValue(dto.getRemarks());
        }
        formComponentValueVoList.add(formComponentValueVo1);
        //明细  循环添加明细
        List<CommodityVo> list = dto.getList();
        List<List> dataList = new ArrayList<>();
        for (CommodityVo data : list) {
            List<Map> maps = new ArrayList<>();
            Map map = new HashMap();
            map.put("name", "名称");
            map.put("value", data.getCommodityName());
            Map map1 = new HashMap();
            map1.put("name", "数量");
            map1.put("value", data.getCommodityAmount());
            Map map2 = new HashMap();
            map2.put("name", "金额");
            map2.put("value", data.getCommodityPrice());
            //            Map map3 = new HashMap();
            //            map3.put("name", "连接");
            //            map3.put("value", data.getCommodityLinks());
            maps.add(map);
            maps.add(map1);
            maps.add(map2);
            // maps.add(map3);
            dataList.add(maps);
        }
        String str = JSON.toJSONString(dataList);
        OapiProcessinstanceCreateRequest.FormComponentValueVo formComponentValueVo2
                = new OapiProcessinstanceCreateRequest.FormComponentValueVo();
        formComponentValueVo2.setName("物品明细");
        formComponentValueVo2.setValue(str);
        formComponentValueVoList.add(formComponentValueVo2);

        //设置审批人，会签、或签设置的审批人必须大于等于2个人
        List<OapiProcessinstanceCreateRequest.ProcessInstanceApproverVo> processInstanceApproverVoList =
                new ArrayList<>();
        //设置审批类型：AND-会签  OR-或签  NONE-单人
        // 判断审批人的数量
        List<String> approverUserid = dto.getApprover_userid();
        for (String data : approverUserid) {
            OapiProcessinstanceCreateRequest.ProcessInstanceApproverVo processInstanceApproverVo =
                    new OapiProcessinstanceCreateRequest.ProcessInstanceApproverVo();
            //设置审批类型：AND-会签  OR-或签  NONE-单人
            // 判断审批人的数量
            processInstanceApproverVo.setTaskActionType("NONE");
            //设置审批人
            processInstanceApproverVo.setUserIds(Arrays.asList(data));
            processInstanceApproverVoList.add(processInstanceApproverVo);
        }
        req.setApproversV2(processInstanceApproverVoList);
        //抄送人
        req.setCcList(StringUtils.join(dto.getCc_userId(), ','));
        // 最后的请求
        req.setFormComponentValues(formComponentValueVoList);
        OapiProcessinstanceCreateResponse rsp = client.execute(req, dto.getAccess_token());
        if (JSONObject.parseObject(rsp.getBody()).get("errmsg").equals("ok")) {
            return String.valueOf(JSONObject.parseObject(rsp.getBody()).get("process_instance_id"));
        }
        throw new AntException((int) JSONObject.parseObject(rsp.getBody()).get("errcode"),
                JSONObject.parseObject(rsp.getBody()).get("errmsg").toString());
    }


    /**
     * 领料申请审批
     * 开发文档 https://open.dingtalk.com/document/orgapp-server/create-an-approval-instance
     *
     * @param dto 关联商品信息
     * @throws ApiException
     */
    public static String OldGoodePickingApprove(DingDto dto) throws Exception {
        DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/processinstance/create");
        OapiProcessinstanceCreateRequest req = new OapiProcessinstanceCreateRequest();
        req.setAgentId(Constants.AGENTID);
        //模板code
        req.setProcessCode(Constants.ALLOCATION_PICKING_REIMBURSEMENT);
        //发起人userId
        req.setOriginatorUserId(dto.getOriginator_userid());
        //发起人部门Id
        req.setDeptId(Long.valueOf(dto.getDeptId()));

        req.setCcPosition("START");
        //申请部门
        List<OapiProcessinstanceCreateRequest.FormComponentValueVo> formComponentValueVoList = new ArrayList<>();

        OapiProcessinstanceCreateRequest.FormComponentValueVo formComponentValueVo =
                new OapiProcessinstanceCreateRequest.FormComponentValueVo();
        formComponentValueVo.setName("申请部门");
        formComponentValueVo.setValue(dto.getCity() + " " + dto.getDepartment());
        formComponentValueVoList.add(formComponentValueVo);
        //业务编码
        OapiProcessinstanceCreateRequest.FormComponentValueVo formComponentValueVo1 =
                new OapiProcessinstanceCreateRequest.FormComponentValueVo();
        formComponentValueVo1.setName("业务编码");
        formComponentValueVo1.setValue(dto.getBusinessCode());
        formComponentValueVoList.add(formComponentValueVo1);

        //备注
        OapiProcessinstanceCreateRequest.FormComponentValueVo formComponentValueVo2 =
                new OapiProcessinstanceCreateRequest.FormComponentValueVo();

        formComponentValueVo2.setName("备注");
        if (dto.getRemarks() == null || dto.getRemarks().equals("")) {
            formComponentValueVo2.setValue("");
        } else {
            formComponentValueVo2.setValue(dto.getRemarks());
        }
        formComponentValueVoList.add(formComponentValueVo2);
        //明细  循环添加明细
        List<PickingCommodityVo> list = dto.getPicList();
        List<List> dataList = new ArrayList<>();
        for (PickingCommodityVo data : list) {
            List<Map> maps = new ArrayList<>();
            Map map = new HashMap();
            map.put("name", "名称");
            map.put("value", data.getCommodityName());
            Map map1 = new HashMap();
            map1.put("name", "数量");
            map1.put("value", data.getApplyNumber());
            maps.add(map);
            maps.add(map1);
            dataList.add(maps);
        }
        String str = JSON.toJSONString(dataList);
        OapiProcessinstanceCreateRequest.FormComponentValueVo formComponentValueVo3
                = new OapiProcessinstanceCreateRequest.FormComponentValueVo();
        formComponentValueVo3.setName("物品明细");
        formComponentValueVo3.setValue(str);
        formComponentValueVoList.add(formComponentValueVo3);

        //设置审批人，会签、或签设置的审批人必须大于等于2个人
//        List<OapiProcessinstanceCreateRequest.ProcessInstanceApproverVo> processInstanceApproverVoList =
//                new ArrayList<>();
//        OapiProcessinstanceCreateRequest.ProcessInstanceApproverVo processInstanceApproverVo =
//                new OapiProcessinstanceCreateRequest.ProcessInstanceApproverVo();
        //设置审批类型：AND-会签  OR-或签  NONE-单人
        // 判断审批人的数量
        //List<String> approverUserid = dto.getApprover_userid();

        //设置审批人，会签、或签设置的审批人必须大于等于2个人
        List<OapiProcessinstanceCreateRequest.ProcessInstanceApproverVo> processInstanceApproverVoList =
                new ArrayList<>();
        //设置审批类型：AND-会签  OR-或签  NONE-单人
        // 判断审批人的数量
        List<String> approverUserid = dto.getApprover_userid();
        for (String data : approverUserid) {
            OapiProcessinstanceCreateRequest.ProcessInstanceApproverVo processInstanceApproverVo =
                    new OapiProcessinstanceCreateRequest.ProcessInstanceApproverVo();
            //设置审批类型：AND-会签  OR-或签  NONE-单人
            // 判断审批人的数量
            processInstanceApproverVo.setTaskActionType("NONE");
            //设置审批人
            processInstanceApproverVo.setUserIds(Arrays.asList(data));
            processInstanceApproverVoList.add(processInstanceApproverVo);
        }

        req.setApproversV2(processInstanceApproverVoList);
        //抄送人
        req.setCcList(StringUtils.join(dto.getCc_userId(), ','));


//        if (approverUserid.size() == 1) {
//            processInstanceApproverVo.setTaskActionType("NONE");
//        } else {
//            processInstanceApproverVo.setTaskActionType("AND");
//        }


        //设置审批人
//        processInstanceApproverVo.setUserIds(approverUserid);
//        processInstanceApproverVoList.add(processInstanceApproverVo);
//        req.setApproversV2(processInstanceApproverVoList);
        //抄送人
     //   req.setCcList(StringUtils.join(dto.getCc_userId(), ','));
        // 最后的请求
        req.setFormComponentValues(formComponentValueVoList);
        OapiProcessinstanceCreateResponse rsp = client.execute(req, dto.getAccess_token());
        if (JSONObject.parseObject(rsp.getBody()).get("errmsg").equals("ok")) {
            return String.valueOf(JSONObject.parseObject(rsp.getBody()).get("process_instance_id"));
        }
        throw new AntException((int) JSONObject.parseObject(rsp.getBody()).get("errcode"),
                JSONObject.parseObject(rsp.getBody()).get("errmsg").toString());
    }


    /**
     * 采购员请款审批
     * 开发文档 https://open.dingtalk.com/document/orgapp-server/create-an-approval-instance
     *
     * @param dto 采购员请款审批
     * @throws ApiException
     */
    public static String OldPurchaseRequest(FundsDto dto) throws Exception {
        DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/processinstance/create");
        OapiProcessinstanceCreateRequest req = new OapiProcessinstanceCreateRequest();
        req.setAgentId(Constants.AGENTID);
        //模板code
        req.setProcessCode(Constants.ALLOCATION_PURCHASE_PURCHASE);
        //发起人userId
        req.setOriginatorUserId(dto.getOriginator_userid());
        //发起人部门Id
        req.setDeptId(Long.valueOf(dto.getDeptId()));
        req.setCcPosition("START");

        //申请部门
        List<OapiProcessinstanceCreateRequest.FormComponentValueVo> formComponentValueVoList = new ArrayList<>();

        OapiProcessinstanceCreateRequest.FormComponentValueVo formComponentValueVo =
                new OapiProcessinstanceCreateRequest.FormComponentValueVo();

        formComponentValueVo.setName("日期");
        formComponentValueVo.setValue(dto.getDate());

        OapiProcessinstanceCreateRequest.FormComponentValueVo formComponentValueVo1 =
                new OapiProcessinstanceCreateRequest.FormComponentValueVo();

        formComponentValueVo1.setName("公司名称");
        formComponentValueVo1.setValue(dto.getDepartment());


        OapiProcessinstanceCreateRequest.FormComponentValueVo formComponentValueVo2 =
                new OapiProcessinstanceCreateRequest.FormComponentValueVo();

        formComponentValueVo2.setName("紧急程度");
        formComponentValueVo2.setValue(dto.getUrgency());

        OapiProcessinstanceCreateRequest.FormComponentValueVo formComponentValueVo3 =
                new OapiProcessinstanceCreateRequest.FormComponentValueVo();

        formComponentValueVo3.setName("请款事由");
        formComponentValueVo3.setValue(dto.getReason() == null ? "" : dto.getReason());

        OapiProcessinstanceCreateRequest.FormComponentValueVo formComponentValueVo4 =
                new OapiProcessinstanceCreateRequest.FormComponentValueVo();

        formComponentValueVo4.setName("请款金额（元）");
        formComponentValueVo4.setValue(dto.getAmount());

        OapiProcessinstanceCreateRequest.FormComponentValueVo formComponentValueVo5 =
                new OapiProcessinstanceCreateRequest.FormComponentValueVo();

        formComponentValueVo5.setName("收款单位");
        formComponentValueVo5.setValue(dto.getUnit());

        OapiProcessinstanceCreateRequest.FormComponentValueVo formComponentValueVo6 =
                new OapiProcessinstanceCreateRequest.FormComponentValueVo();

        formComponentValueVo6.setName("开户行名称");
        formComponentValueVo6.setValue(dto.getBankName());

        OapiProcessinstanceCreateRequest.FormComponentValueVo formComponentValueVo7 =
                new OapiProcessinstanceCreateRequest.FormComponentValueVo();
        formComponentValueVo7.setName("帐号");
        formComponentValueVo7.setValue(dto.getBankAccount());

        OapiProcessinstanceCreateRequest.FormComponentValueVo formComponentValueVo8 =
                new OapiProcessinstanceCreateRequest.FormComponentValueVo();

        formComponentValueVo8.setName("支付方式");
        formComponentValueVo8.setValue(dto.getPayType());

        formComponentValueVoList.add(formComponentValueVo);
        formComponentValueVoList.add(formComponentValueVo1);
        formComponentValueVoList.add(formComponentValueVo2);
        formComponentValueVoList.add(formComponentValueVo3);
        formComponentValueVoList.add(formComponentValueVo4);
        formComponentValueVoList.add(formComponentValueVo5);
        formComponentValueVoList.add(formComponentValueVo6);
        formComponentValueVoList.add(formComponentValueVo7);
        formComponentValueVoList.add(formComponentValueVo8);

        //设置审批人，会签、或签设置的审批人必须大于等于2个人
        List<OapiProcessinstanceCreateRequest.ProcessInstanceApproverVo> processInstanceApproverVoList =
                new ArrayList<>();
        //设置审批类型：AND-会签  OR-或签  NONE-单人
        // 判断审批人的数量
        List<String> approverUserid = dto.getApprover_userid();
        for (String data : approverUserid) {
            OapiProcessinstanceCreateRequest.ProcessInstanceApproverVo processInstanceApproverVo =
                    new OapiProcessinstanceCreateRequest.ProcessInstanceApproverVo();
            //设置审批类型：AND-会签  OR-或签  NONE-单人
            // 判断审批人的数量
            processInstanceApproverVo.setTaskActionType("NONE");
            //设置审批人
            processInstanceApproverVo.setUserIds(Arrays.asList(data));
            processInstanceApproverVoList.add(processInstanceApproverVo);
        }

        req.setApproversV2(processInstanceApproverVoList);
        //抄送人
        req.setCcList(StringUtils.join(dto.getCc_userId(), ','));
        // 最后的请求
        req.setFormComponentValues(formComponentValueVoList);
        OapiProcessinstanceCreateResponse rsp = client.execute(req, dto.getAccess_token());
        if (JSONObject.parseObject(rsp.getBody()).get("errmsg").equals("ok")) {
            return String.valueOf(JSONObject.parseObject(rsp.getBody()).get("process_instance_id"));
        }
        throw new AntException((int) JSONObject.parseObject(rsp.getBody()).get("errcode"),
                JSONObject.parseObject(rsp.getBody()).get("errmsg").toString());
    }


    /**
     * 采购员报销审批
     * 开发文档 https://open.dingtalk.com/document/orgapp-server/create-an-approval-instance
     *
     * @param dto 关联商品信息
     * @throws ApiException
     */
    public static String OldReimbursement(FundsDto dto) throws Exception {
        DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/processinstance/create");
        OapiProcessinstanceCreateRequest req = new OapiProcessinstanceCreateRequest();
        req.setAgentId(Constants.AGENTID);
        //模板code
        req.setProcessCode(Constants.ALLOCATION_PURCHASE_REIMBURSEMENT);
        //发起人userId
        req.setOriginatorUserId(dto.getOriginator_userid());
        //发起人部门Id
        req.setDeptId(Long.valueOf(dto.getDeptId()));
        req.setCcPosition("START");
        //申请部门
        List<OapiProcessinstanceCreateRequest.FormComponentValueVo> formComponentValueVoList = new ArrayList<>();
        OapiProcessinstanceCreateRequest.FormComponentValueVo formComponentValueVo1 =
                new OapiProcessinstanceCreateRequest.FormComponentValueVo();

        formComponentValueVo1.setName("日期");
        formComponentValueVo1.setValue(dto.getDate());

        OapiProcessinstanceCreateRequest.FormComponentValueVo formComponentValueVo2 =
                new OapiProcessinstanceCreateRequest.FormComponentValueVo();

        formComponentValueVo2.setName("公司名称");
        formComponentValueVo2.setValue(dto.getCompanyName());

        OapiProcessinstanceCreateRequest.FormComponentValueVo formComponentValueVo3 =
                new OapiProcessinstanceCreateRequest.FormComponentValueVo();
        formComponentValueVo3.setName("紧急程度");
        formComponentValueVo3.setValue(dto.getUrgency());
        formComponentValueVoList.add(formComponentValueVo1);
        //明细  循环添加明细
        List<ReimbursementProjectDto> list = dto.getProjectDtoList();
        String str = "";
        if (list != null && list.size() > 0) {
            List<List> dataList = new ArrayList<>();
            for (ReimbursementProjectDto data : list) {
                List<Map> maps = new ArrayList<>();
                Map map = new HashMap();
                map.put("name", "项目");
                map.put("value", data.getProjectName());
                Map map1 = new HashMap();
                map1.put("name", "金额");
                map1.put("value", data.getProjectPrice());
                maps.add(map);
                maps.add(map1);
                dataList.add(maps);
            }
            str = JSON.toJSONString(dataList);
        }
        // String str = JSON.toJSONString(dataList);
        //明细
        OapiProcessinstanceCreateRequest.FormComponentValueVo formComponentValueVo4
                = new OapiProcessinstanceCreateRequest.FormComponentValueVo();
        formComponentValueVo4.setName("明细");
        formComponentValueVo4.setValue(str);

        OapiProcessinstanceCreateRequest.FormComponentValueVo formComponentValueVo5 =
                new OapiProcessinstanceCreateRequest.FormComponentValueVo();

        formComponentValueVo5.setName("请款事由");
        formComponentValueVo5.setValue(dto.getReason() == null ? "" : dto.getReason()); //reason

        OapiProcessinstanceCreateRequest.FormComponentValueVo formComponentValueVo6 =
                new OapiProcessinstanceCreateRequest.FormComponentValueVo();
        formComponentValueVo6.setName("报销金额（元）");
        formComponentValueVo6.setValue(dto.getAmount());

        OapiProcessinstanceCreateRequest.FormComponentValueVo formComponentValueVo7 =
                new OapiProcessinstanceCreateRequest.FormComponentValueVo();
        formComponentValueVo7.setName("图片");
        formComponentValueVo7.setValue(JSONObject.toJSONString(dto.getPicture()));

        formComponentValueVoList.add(formComponentValueVo1);
        formComponentValueVoList.add(formComponentValueVo2);
        formComponentValueVoList.add(formComponentValueVo3);
        formComponentValueVoList.add(formComponentValueVo4);
        formComponentValueVoList.add(formComponentValueVo5);
        formComponentValueVoList.add(formComponentValueVo6);
        formComponentValueVoList.add(formComponentValueVo7);

        //设置审批人，会签、或签设置的审批人必须大于等于2个人
        List<OapiProcessinstanceCreateRequest.ProcessInstanceApproverVo> processInstanceApproverVoList =
                new ArrayList<>();
        //设置审批类型：AND-会签  OR-或签  NONE-单人
        // 判断审批人的数量
        List<String> approverUserid = dto.getApprover_userid();
        for (String data : approverUserid) {
            OapiProcessinstanceCreateRequest.ProcessInstanceApproverVo processInstanceApproverVo =
                    new OapiProcessinstanceCreateRequest.ProcessInstanceApproverVo();
            //设置审批类型：AND-会签  OR-或签  NONE-单人
            // 判断审批人的数量
            processInstanceApproverVo.setTaskActionType("NONE");
            //设置审批人
            processInstanceApproverVo.setUserIds(Arrays.asList(data));
            processInstanceApproverVoList.add(processInstanceApproverVo);
        }
        //设置审批人
        req.setApproversV2(processInstanceApproverVoList);
        //抄送人
        req.setCcList(StringUtils.join(dto.getCc_userId(), ','));
        // 最后的请求
        req.setFormComponentValues(formComponentValueVoList);

        OapiProcessinstanceCreateResponse rsp = client.execute(req, dto.getAccess_token());
        if (JSONObject.parseObject(rsp.getBody()).get("errmsg").equals("ok")) {
            return String.valueOf(JSONObject.parseObject(rsp.getBody()).get("process_instance_id"));
        }
        return "201";
        //return JSONObject.parseObject(rsp.getBody()).get("errcode").toString();
        // throw new AntException((int) JSONObject.parseObject(rsp.getBody()).get("errcode"),
        //       JSONObject.parseObject(rsp.getBody()).get("errmsg").toString());
    }


    /**
     * 采购日常员报销审批
     * 开发文档 https://open.dingtalk.com/document/orgapp-server/create-an-approval-instance
     *
     * @param dto 关联商品信息
     * @throws ApiException
     */
    public static String Reimbursement(FundsDto dto) throws Exception {
        DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/processinstance/create");
        OapiProcessinstanceCreateRequest req = new OapiProcessinstanceCreateRequest();
        req.setAgentId(Constants.AGENTID);
        //模板code
        req.setProcessCode(Constants.ALLOCATION_PROCURE_REIMBURSEMENT);
        //发起人userId
        req.setOriginatorUserId(dto.getOriginator_userid());
        //发起人部门Id
        req.setDeptId(Long.valueOf(dto.getDeptId()));
        req.setCcPosition("START");
        //申请部门
        List<OapiProcessinstanceCreateRequest.FormComponentValueVo> formComponentValueVoList = new ArrayList<>();
        OapiProcessinstanceCreateRequest.FormComponentValueVo formComponentValueVo1 =
                new OapiProcessinstanceCreateRequest.FormComponentValueVo();

        formComponentValueVo1.setName("日期");
        formComponentValueVo1.setValue(dto.getDate());

        OapiProcessinstanceCreateRequest.FormComponentValueVo formComponentValueVo2 =
                new OapiProcessinstanceCreateRequest.FormComponentValueVo();

        formComponentValueVo2.setName("公司名称");
        formComponentValueVo2.setValue(dto.getCompanyName());

        OapiProcessinstanceCreateRequest.FormComponentValueVo formComponentValueVo3 =
                new OapiProcessinstanceCreateRequest.FormComponentValueVo();
        formComponentValueVo3.setName("紧急程度");
        formComponentValueVo3.setValue(dto.getUrgency());
        formComponentValueVoList.add(formComponentValueVo1);
        //明细  循环添加明细
        List<ReimbursementProjectDto> list = dto.getProjectDtoList();
        String str = "";
        if (list != null && list.size() > 0) {
            List<List> dataList = new ArrayList<>();
            for (ReimbursementProjectDto data : list) {
                List<Map> maps = new ArrayList<>();
                Map map = new HashMap();
                map.put("name", "项目");
                map.put("value", data.getProjectName());

                Map map1 = new HashMap();
                map1.put("name", "数量");
                map1.put("value", data.getAmount() == null ? '0' : data.getAmount());

                Map map2 = new HashMap();
                map2.put("name", "金额");
                map2.put("value", data.getProjectPrice());

                BigDecimal num = data.getAmount() == null ? new BigDecimal('0') : new BigDecimal(data.getAmount());
                BigDecimal p = data.getProjectPrice().multiply(num).setScale(2, BigDecimal.ROUND_HALF_UP);
                Map map3 = new HashMap();
                map3.put("name", "合计");
                map3.put("value", p.toString());

                maps.add(map);
                maps.add(map1);
                maps.add(map2);
                maps.add(map3);
                dataList.add(maps);
            }
            str = JSON.toJSONString(dataList);
        }
        //明细
        OapiProcessinstanceCreateRequest.FormComponentValueVo formComponentValueVo4
                = new OapiProcessinstanceCreateRequest.FormComponentValueVo();
        formComponentValueVo4.setName("明细");
        formComponentValueVo4.setValue(str);

        OapiProcessinstanceCreateRequest.FormComponentValueVo formComponentValueVo5 =
                new OapiProcessinstanceCreateRequest.FormComponentValueVo();

        formComponentValueVo5.setName("请款事由");
        formComponentValueVo5.setValue(dto.getReason() == null ? "" : dto.getReason()); //reason

        OapiProcessinstanceCreateRequest.FormComponentValueVo formComponentValueVo6 =
                new OapiProcessinstanceCreateRequest.FormComponentValueVo();
        formComponentValueVo6.setName("报销金额（元）");
        formComponentValueVo6.setValue(dto.getAmount());

        OapiProcessinstanceCreateRequest.FormComponentValueVo formComponentValueVo7 =
                new OapiProcessinstanceCreateRequest.FormComponentValueVo();
        formComponentValueVo7.setName("图片");
        formComponentValueVo7.setValue(JSONObject.toJSONString(dto.getPicture()));

        formComponentValueVoList.add(formComponentValueVo1);
        formComponentValueVoList.add(formComponentValueVo2);
        formComponentValueVoList.add(formComponentValueVo3);
        formComponentValueVoList.add(formComponentValueVo4);
        formComponentValueVoList.add(formComponentValueVo5);
        formComponentValueVoList.add(formComponentValueVo6);
        formComponentValueVoList.add(formComponentValueVo7);

        //设置审批人，会签、或签设置的审批人必须大于等于2个人
        List<OapiProcessinstanceCreateRequest.ProcessInstanceApproverVo> processInstanceApproverVoList =
                new ArrayList<>();
        //设置审批类型：AND-会签  OR-或签  NONE-单人
        // 判断审批人的数量
        List<String> approverUserid = dto.getApprover_userid();
        for (String data : approverUserid) {
            OapiProcessinstanceCreateRequest.ProcessInstanceApproverVo processInstanceApproverVo =
                    new OapiProcessinstanceCreateRequest.ProcessInstanceApproverVo();
            //设置审批类型：AND-会签  OR-或签  NONE-单人
            // 判断审批人的数量
            processInstanceApproverVo.setTaskActionType("NONE");
            //设置审批人
            processInstanceApproverVo.setUserIds(Arrays.asList(data));
            processInstanceApproverVoList.add(processInstanceApproverVo);
        }
        //设置审批人
        req.setApproversV2(processInstanceApproverVoList);
        //抄送人
        req.setCcList(StringUtils.join(dto.getCc_userId(), ','));
        // 最后的请求
        req.setFormComponentValues(formComponentValueVoList);

        OapiProcessinstanceCreateResponse rsp = client.execute(req, dto.getAccess_token());
        if (JSONObject.parseObject(rsp.getBody()).get("errmsg").equals("ok")) {
            return String.valueOf(JSONObject.parseObject(rsp.getBody()).get("process_instance_id"));
        }else{
            return "201";
        }
        //return JSONObject.parseObject(rsp.getBody()).get("errcode").toString();
        // throw new AntException((int) JSONObject.parseObject(rsp.getBody()).get("errcode"),
        //       JSONObject.parseObject(rsp.getBody()).get("errmsg").toString());
    }

    /**
     * 请款
     *
     * @param dto 关联商品信息
     * @throws ApiException
     */
    public static String OldRequestFunds(FundsDto dto) throws Exception {
        DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/processinstance/create");
        OapiProcessinstanceCreateRequest req = new OapiProcessinstanceCreateRequest();
        req.setAgentId(Constants.AGENTID);
        //模板code
        req.setProcessCode(Constants.ALLOCATION_PURCHASE_REQUESTFUNDS);
        //发起人userId
        req.setOriginatorUserId(dto.getOriginator_userid());
        //发起人部门Id
        req.setDeptId(Long.valueOf(dto.getDeptId()));
        req.setCcPosition("START");
        //申请部门
        List<OapiProcessinstanceCreateRequest.FormComponentValueVo> formComponentValueVoList = new ArrayList<>();


        OapiProcessinstanceCreateRequest.FormComponentValueVo formComponentValueVo0 =
                new OapiProcessinstanceCreateRequest.FormComponentValueVo();

        formComponentValueVo0.setName("项目名称");
        formComponentValueVo0.setValue(dto.getProjectName()== null ? "" : dto.getProjectName());


        OapiProcessinstanceCreateRequest.FormComponentValueVo formComponentValueVo1 =
                new OapiProcessinstanceCreateRequest.FormComponentValueVo();

        formComponentValueVo1.setName("日期");
        formComponentValueVo1.setValue(dto.getDate());

        OapiProcessinstanceCreateRequest.FormComponentValueVo formComponentValueVo2 =
                new OapiProcessinstanceCreateRequest.FormComponentValueVo();

        formComponentValueVo2.setName("公司名称");
        formComponentValueVo2.setValue(dto.getCompanyName());

        OapiProcessinstanceCreateRequest.FormComponentValueVo formComponentValueVo3 =
                new OapiProcessinstanceCreateRequest.FormComponentValueVo();
        formComponentValueVo3.setName("紧急程度");
        formComponentValueVo3.setValue(dto.getUrgency());
        formComponentValueVoList.add(formComponentValueVo1);
        //明细  循环添加明细
        List<ReimbursementProjectDto> list = dto.getProjectDtoList();
        String str = "";
        if (list != null && list.size() > 0) {
            List<List> dataList = new ArrayList<>();
            for (ReimbursementProjectDto data : list) {
                List<Map> maps = new ArrayList<>();
                Map map = new HashMap();
                map.put("name", "项目");
                map.put("value", data.getProjectName());

                Map map2 = new HashMap();
                map2.put("name", "金额");
                map2.put("value", data.getProjectPrice());
                maps.add(map);
                maps.add(map2);
                dataList.add(maps);
            }
            str = JSON.toJSONString(dataList);
        }

        //明细
        OapiProcessinstanceCreateRequest.FormComponentValueVo formComponentValueVo4
                = new OapiProcessinstanceCreateRequest.FormComponentValueVo();
        formComponentValueVo4.setName("明细");
        formComponentValueVo4.setValue(str);

        OapiProcessinstanceCreateRequest.FormComponentValueVo formComponentValueVo5 =
                new OapiProcessinstanceCreateRequest.FormComponentValueVo();

        formComponentValueVo5.setName("请款事由");
        formComponentValueVo5.setValue(dto.getReason() == null ? "" : dto.getReason()); //reason

        OapiProcessinstanceCreateRequest.FormComponentValueVo formComponentValueVo6 =
                new OapiProcessinstanceCreateRequest.FormComponentValueVo();
        formComponentValueVo6.setName("请款金额（元）");
        formComponentValueVo6.setValue(dto.getAmount());

        OapiProcessinstanceCreateRequest.FormComponentValueVo formComponentValueVo7 =
                new OapiProcessinstanceCreateRequest.FormComponentValueVo();
        formComponentValueVo7.setName("收款单位");
        formComponentValueVo7.setValue(dto.getUnit() == null ? "" : dto.getUnit());

        OapiProcessinstanceCreateRequest.FormComponentValueVo formComponentValueVo8 =
                new OapiProcessinstanceCreateRequest.FormComponentValueVo();
        formComponentValueVo8.setName("开户行名称");
        formComponentValueVo8.setValue(dto.getBankName() == null ? "" : dto.getBankName());

        OapiProcessinstanceCreateRequest.FormComponentValueVo formComponentValueVo9 =
                new OapiProcessinstanceCreateRequest.FormComponentValueVo();
        formComponentValueVo9.setName("帐号");
        formComponentValueVo9.setValue(dto.getBankAccount() == null ? "" : dto.getBankAccount());

        OapiProcessinstanceCreateRequest.FormComponentValueVo formComponentValueVo10 =
                new OapiProcessinstanceCreateRequest.FormComponentValueVo();
        formComponentValueVo10.setName("图片");
        formComponentValueVo10.setValue(JSONObject.toJSONString(dto.getPicture()));

        OapiProcessinstanceCreateRequest.FormComponentValueVo formComponentValueVo11 =
                new OapiProcessinstanceCreateRequest.FormComponentValueVo();
        formComponentValueVo11.setName("附件");
        formComponentValueVo11.setValue(JSONObject.toJSONString(dto.getAnnex()));

        formComponentValueVoList.add(formComponentValueVo1);
        formComponentValueVoList.add(formComponentValueVo2);
        formComponentValueVoList.add(formComponentValueVo3);
        formComponentValueVoList.add(formComponentValueVo4);
        formComponentValueVoList.add(formComponentValueVo5);
        formComponentValueVoList.add(formComponentValueVo6);
        formComponentValueVoList.add(formComponentValueVo7);
        formComponentValueVoList.add(formComponentValueVo8);
        formComponentValueVoList.add(formComponentValueVo9);
        formComponentValueVoList.add(formComponentValueVo10);
        formComponentValueVoList.add(formComponentValueVo11);

        List<OapiProcessinstanceCreateRequest.ProcessInstanceApproverVo> processInstanceApproverVoList =
                new ArrayList<>();
        //设置审批人，会签、或签设置的审批人必须大于等于2个人
        List<String> approverUserid = dto.getApprover_userid();
        for (String data : approverUserid) {
            OapiProcessinstanceCreateRequest.ProcessInstanceApproverVo processInstanceApproverVo =
                    new OapiProcessinstanceCreateRequest.ProcessInstanceApproverVo();
            //设置审批类型：AND-会签  OR-或签  NONE-单人
            // 判断审批人的数量
            processInstanceApproverVo.setTaskActionType("NONE");
            //设置审批人
            processInstanceApproverVo.setUserIds(Arrays.asList(data));
            processInstanceApproverVoList.add(processInstanceApproverVo);
        }
        req.setApproversV2(processInstanceApproverVoList);

        //抄送人
        req.setCcList(StringUtils.join(dto.getCc_userId(), ','));
        // 最后的请求
        req.setFormComponentValues(formComponentValueVoList);
        System.out.println(req);

        OapiProcessinstanceCreateResponse rsp = client.execute(req, dto.getAccess_token());
        if (JSONObject.parseObject(rsp.getBody()).get("errmsg").equals("ok")) {
            return String.valueOf(JSONObject.parseObject(rsp.getBody()).get("process_instance_id"));
        } else {
            return "201";
        }
       //return "201";
        //       throw new AntException((int) JSONObject.parseObject(rsp.getBody()).get("errcode"),
        //                JSONObject.parseObject(rsp.getBody()).get("errmsg").toString());
    }


    /**
     * @param allocation 关联商品信息
     * @throws ApiException
     */
    public static String OldExamineAndApprove(Allocation allocation, String access_token) throws ApiException {
        DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/processinstance/create");
        OapiProcessinstanceCreateRequest req = new OapiProcessinstanceCreateRequest();
        req.setAgentId(Constants.AGENTID);
        //模板code
        req.setProcessCode(Constants.ALLOCATION_PROCESSCODE);
        //发起人userId
        req.setOriginatorUserId(allocation.getStaff_userid());
        //发起人部门Id
        req.setDeptId((long) allocation.getStaff_dept_id());
        req.setCcList(allocation.getCc_list_userid());
        req.setCcPosition("START");

        //申请部门
        List<OapiProcessinstanceCreateRequest.FormComponentValueVo> formComponentValueVoList = new ArrayList<>();

        OapiProcessinstanceCreateRequest.FormComponentValueVo formComponentValueVo =
                new OapiProcessinstanceCreateRequest.FormComponentValueVo();
        formComponentValueVoList.add(formComponentValueVo);
        formComponentValueVo.setName("申请部门");
        formComponentValueVo.setValue(allocation.getSupply_city().getName() + " " + allocation.getSupply_dept().getName());
        //供货部门
        OapiProcessinstanceCreateRequest.FormComponentValueVo formComponentValueVo7 =
                new OapiProcessinstanceCreateRequest.FormComponentValueVo();
        formComponentValueVoList.add(formComponentValueVo7);
        formComponentValueVo7.setName("供货部门");
        formComponentValueVo7.setValue(allocation.getExtract_city().getName() + " " + allocation.getExtract_dept().getName());
        //备注
        OapiProcessinstanceCreateRequest.FormComponentValueVo formComponentValueVo1 =
                new OapiProcessinstanceCreateRequest.FormComponentValueVo();
        formComponentValueVoList.add(formComponentValueVo1);
        formComponentValueVo1.setName("备注");
        if (allocation.getAllocation_remarks() == null || allocation.getAllocation_remarks().equals("")) {
            formComponentValueVo1.setValue("");
        } else {
            formComponentValueVo1.setValue(allocation.getAllocation_remarks());
        }

        //明细  循环添加明细
        for (int a = 0; a < allocation.getAllocationAndCommodity().size(); a++) {
            OapiProcessinstanceCreateRequest.FormComponentValueVo formComponentValueVo12 =
                    new OapiProcessinstanceCreateRequest.FormComponentValueVo();
            OapiProcessinstanceCreateRequest.FormComponentValueVo Item1 =
                    new OapiProcessinstanceCreateRequest.FormComponentValueVo();
            Item1.setName("名称");
            Item1.setValue(allocation.getAllocationAndCommodity().get(a).getCommodity().getCommodityName());
            OapiProcessinstanceCreateRequest.FormComponentValueVo Item2 =
                    new OapiProcessinstanceCreateRequest.FormComponentValueVo();
            Item2.setName("型号");
            if (allocation.getAllocationAndCommodity().get(a).getCommodity().getCommodityModel() == null || allocation.getAllocationAndCommodity().get(a).getCommodity().getCommodityModel().equals("")) {
                Item2.setValue("");
            } else {
                Item2.setValue(allocation.getAllocationAndCommodity().get(a).getCommodity().getCommodityModel());
            }
            OapiProcessinstanceCreateRequest.FormComponentValueVo Item3 =
                    new OapiProcessinstanceCreateRequest.FormComponentValueVo();
            Item3.setName("规格");
            if (allocation.getAllocationAndCommodity().get(a).getCommodity().getCommoditySpecification() == null || allocation.getAllocationAndCommodity().get(a).getCommodity().getCommoditySpecification().equals("")) {
                Item3.setValue("");
            } else {
                Item3.setValue(allocation.getAllocationAndCommodity().get(a).getCommodity().getCommoditySpecification());
            }
            OapiProcessinstanceCreateRequest.FormComponentValueVo Item4 =
                    new OapiProcessinstanceCreateRequest.FormComponentValueVo();
            Item4.setName("数量");
            Item4.setValue(allocation.getAllocationAndCommodity().get(a).getCommodity_allocation_quantity().toString());
            formComponentValueVo12.setName("申请详情(" + (a + 1) + ")");
            formComponentValueVo12.setValue(JSON.toJSONString(Arrays.asList(Arrays.asList(Item1, Item2, Item3, Item4))));
            formComponentValueVoList.add(formComponentValueVo12);
        }
        //设置审批人，会签、或签设置的审批人必须大于等于2个人
        List<OapiProcessinstanceCreateRequest.ProcessInstanceApproverVo> processInstanceApproverVoList =
                new ArrayList<>();
        OapiProcessinstanceCreateRequest.ProcessInstanceApproverVo processInstanceApproverVo =
                new OapiProcessinstanceCreateRequest.ProcessInstanceApproverVo();
        processInstanceApproverVoList.add(processInstanceApproverVo);
        //设置审批类型：AND-会签  OR-或签  NONE-单人
        processInstanceApproverVo.setTaskActionType("AND");
        //设置审批人  可放置多个审批人的userId
        processInstanceApproverVo.setUserIds(Arrays.asList(allocation.getApprover_userid()));
        req.setApproversV2(processInstanceApproverVoList);

        req.setFormComponentValues(formComponentValueVoList);
        OapiProcessinstanceCreateResponse rsp = client.execute(req, access_token);
        System.out.println(rsp.getBody());
        if (JSONObject.parseObject(rsp.getBody()).get("errmsg").equals("ok")) {
            return String.valueOf(JSONObject.parseObject(rsp.getBody()).get("process_instance_id"));
        }
        throw new AntException((int) JSONObject.parseObject(rsp.getBody()).get("errcode"),
                JSONObject.parseObject(rsp.getBody()).get("errmsg").toString());

    }

    /**
     * 审批撤销
     *
     * @param access_token
     * @param process_instance_id 审批实例id
     * @throws ApiException
     */
    public static String examineAndApproveRevoke(String access_token, String process_instance_id) throws ApiException {
        DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/process/instance/terminate");
        OapiProcessInstanceTerminateRequest req = new OapiProcessInstanceTerminateRequest();
        OapiProcessInstanceTerminateRequest.TerminateProcessInstanceRequestV2 processInstanceRequestV2 =
                new OapiProcessInstanceTerminateRequest.TerminateProcessInstanceRequestV2();
        processInstanceRequestV2.setProcessInstanceId(process_instance_id);
        processInstanceRequestV2.setIsSystem(true);
        req.setRequest(processInstanceRequestV2);
        OapiProcessInstanceTerminateResponse rsp = client.execute(req, access_token);
        return JSONObject.parseObject(rsp.getBody()).get("errcode").toString();

        //        if (Integer.parseInt(JSONObject.parseObject(rsp.getBody()).get("errcode").toString()) == 0) {
        //            return Resulto.success("ok");
        //        }
        //        throw new AntException((int) JSONObject.parseObject(rsp.getBody()).get("errcode"),
        //                JSONObject.parseObject(rsp.getBody()).get("errmsg").toString());
    }
    //    public static ResultVo examineAndApproveRevoke(String access_token, String process_instance_id) throws
    //    ApiException {
    //        DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk" +
    //                ".com/topapi/process/instance/terminate");
    //        OapiProcessInstanceTerminateRequest req = new OapiProcessInstanceTerminateRequest();
    //        OapiProcessInstanceTerminateRequest.TerminateProcessInstanceRequestV2 processInstanceRequestV2 =
    //                new OapiProcessInstanceTerminateRequest.TerminateProcessInstanceRequestV2();
    //        processInstanceRequestV2.setProcessInstanceId(process_instance_id);
    //        processInstanceRequestV2.setIsSystem(true);
    //        req.setRequest(processInstanceRequestV2);
    //        OapiProcessInstanceTerminateResponse rsp = client.execute(req, access_token);
    //        if (Integer.parseInt(JSONObject.parseObject(rsp.getBody()).get("errcode").toString()) == 0) {
    //            return ResultVo.success("ok");
    //        }
    //        throw new AntException((int) JSONObject.parseObject(rsp.getBody()).get("errcode"),
    //                JSONObject.parseObject(rsp.getBody()).get("errmsg").toString());
    //    }

    /**
     * 撤销功能
     * @return
     */
    //    public static Boolean approvalRevoke(String processInstanceId,String userId) throws Exception {
    //        com.aliyun.dingtalkworkflow_1_0.Client client = DingTalkTool.createClient();
    //        com.aliyun.dingtalkworkflow_1_0.models.TerminateProcessInstanceHeaders terminateProcessInstanceHeaders
    //        = new com.aliyun.dingtalkworkflow_1_0.models.TerminateProcessInstanceHeaders();
    //        terminateProcessInstanceHeaders.xAcsDingtalkAccessToken = getAccessToken();
    //        com.aliyun.dingtalkworkflow_1_0.models.TerminateProcessInstanceRequest terminateProcessInstanceRequest
    //        = new com.aliyun.dingtalkworkflow_1_0.models.TerminateProcessInstanceRequest()
    //                .setProcessInstanceId(processInstanceId)
    //                .setOperatingUserId(userId);
    //        try {
    //            TerminateProcessInstanceResponse data = client.terminateProcessInstanceWithOptions
    //            (terminateProcessInstanceRequest, terminateProcessInstanceHeaders, new com.aliyun.teautil.models
    //            .RuntimeOptions());
    //            return data.body.result;
    //        } catch (TeaException err) {
    //            if (!com.aliyun.teautil.Common.empty(err.code) && !com.aliyun.teautil.Common.empty(err.message)) {
    //                // err 中含有 code 和 message 属性，可帮助开发定位问题
    //                System.out.println(err.code+"          "+err.message);
    //            }
    //        } catch (Exception _err) {
    //            TeaException err = new TeaException(_err.getMessage(), _err);
    //            if (!com.aliyun.teautil.Common.empty(err.code) && !com.aliyun.teautil.Common.empty(err.message)) {
    //                // err 中含有 code 和 message 属性，可帮助开发定位问题
    //                System.out.println(err.code+"          "+err.message);
    //            }
    //        }
    //        return false;
    //    }

    /**
     * 发起采购申请
     *
     * @param
     * @throws ApiException
     */
    public static String appiy(AuditList auditList, String access_token) throws ApiException {
        DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/processinstance/create");
        OapiProcessinstanceCreateRequest req = new OapiProcessinstanceCreateRequest();
        req.setAgentId(Constants.AGENTID);
        //模板code
        req.setProcessCode(Constants.ALLOCATION_APPIY_PROCESSCODE);
        //发起人userId
        req.setOriginatorUserId(auditList.getNameId().toString());
        //发起人部门Id
        req.setDeptId((long) auditList.getDepId());

        req.setCcList(auditList.getNameId().toString());

        req.setCcPosition("START");

        //申请部门
        List<OapiProcessinstanceCreateRequest.FormComponentValueVo> formComponentValueVoList = new ArrayList<>();
        OapiProcessinstanceCreateRequest.FormComponentValueVo formComponentValueVo =
                new OapiProcessinstanceCreateRequest.FormComponentValueVo();
        formComponentValueVoList.add(formComponentValueVo);
        formComponentValueVo.setName("申请部门");
        formComponentValueVo.setValue(auditList.getSupply_city().getName() + " " + auditList.getSupply_dept().getName());

        //备注
        OapiProcessinstanceCreateRequest.FormComponentValueVo formComponentValueVo1 =
                new OapiProcessinstanceCreateRequest.FormComponentValueVo();
        formComponentValueVoList.add(formComponentValueVo1);
        formComponentValueVo1.setName("备注");

        if (auditList.getRemarks() == null || auditList.getRemarks().equals("")) {
            formComponentValueVo1.setValue("");
        } else {
            formComponentValueVo1.setValue(auditList.getRemarks());
        }


        //设置审批人，会签、或签设置的审批人必须大于等于2个人
        List<OapiProcessinstanceCreateRequest.ProcessInstanceApproverVo> processInstanceApproverVoList =
                new ArrayList<>();
        OapiProcessinstanceCreateRequest.ProcessInstanceApproverVo processInstanceApproverVo =
                new OapiProcessinstanceCreateRequest.ProcessInstanceApproverVo();
        processInstanceApproverVoList.add(processInstanceApproverVo);
        //设置审批类型：AND-会签  OR-或签  NONE-单人
        processInstanceApproverVo.setTaskActionType("AND");
        //设置审批人  可放置多个审批人的userId
        processInstanceApproverVo.setUserIds(Arrays.asList(auditList.getNameId().toString()));
        req.setApproversV2(processInstanceApproverVoList);
        req.setFormComponentValues(formComponentValueVoList);
        OapiProcessinstanceCreateResponse rsp = client.execute(req, access_token);
        System.out.println(rsp.getBody());
        if (JSONObject.parseObject(rsp.getBody()).get("errmsg").equals("ok")) {
            return String.valueOf(JSONObject.parseObject(rsp.getBody()).get("process_instance_id"));
        }
        throw new AntException((int) JSONObject.parseObject(rsp.getBody()).get("errcode"),
                JSONObject.parseObject(rsp.getBody()).get("errmsg").toString());

    }

}
